import redis
import time
import threading
import json

class TeamCommunication:
    def __init__(self, channel_name):
        self.channel_name = channel_name
        self.redis_client = redis.StrictRedis(host='202.189.9.39', port=6379, db=0)
        self.pubsub = self.redis_client.pubsub()
        self.pubsub.subscribe(self.channel_name)
        # self.start_listening()
        self.messages = None

    def send_message(self, member_name, command, message):
        """发送消息"""
        data = {
            'member_name': member_name,
            'command': command,
            'message': message
        }
        json_data = json.dumps(data)
        self.redis_client.publish(self.channel_name, json_data)

    def listen_messages(self):
        """监听消息"""
        message = self.pubsub.get_message(ignore_subscribe_messages=True, timeout=0.01)
        if message and message['type'] == 'message':
            print(f"收到消息: {message['data'].decode('utf-8')}")

    def unsubscribe_and_close(self):
        """取消订阅并关闭 Redis 连接"""
        self.pubsub.unsubscribe(self.channel_name)
        self.pubsub.close()
        self.redis_client.close()


# team_comm = TeamCommunication('team_channel')

# while True:
#     team_comm.listen_messages()

        
#     # team_comm.send_message('Alice', "APPLY_TEAM" , '2222222222222')